package com.vincent.template.utils;

import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author Vincent Wang
 * @date 2020/12/30 18:51
 */
public class Md5Util {

    private Md5Util() {
    }

    public static String encode(CharSequence content) {
        return md5(content).toUpperCase();
    }

    public static boolean match(CharSequence rawContent, String encodedStr) {
        return encode(rawContent).equals(encodedStr);
    }

    public static String md5(CharSequence content) {
        if (StringUtils.isBlank(content)) {
            return "";
        }
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(content.toString().getBytes());
            byte[] b = md.digest();
            int i;
            StringBuilder builder = new StringBuilder();
            for (byte value : b) {
                i = value;
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    builder.append("0");
                }
                builder.append(Integer.toHexString(i));
            }
            return builder.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }
}
